﻿using Opc.Ua;
using Opc.Ua.Client;
using SampleTcp;
using SHRIS.MIS.Common.Util.Extension;
using SHRIS.MIS.Entity.ScadaBaseInfo;
using SHRIS.MIS.Entity.ScadaData;
using SHRIS.MIS.Service.OpcService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace SHRIS.MIS.Service.Device
{
    public class ThreeCoordinatesMeasure_11 : BasicDevice
    {
        private readonly IEnumerable<OpcDataSourceEntity> _opcDataSourceEntities;

        private TcpListening tcpListener;

        private Guid opcServiceId;


        private MessageResponseContent messageResponseContent = new MessageResponseContent();


        public ThreeCoordinatesMeasure_11(DeviceEntity deviceEntity,
           WorkshopCommunicationService workshopCommunicationService,
           IEnumerable<OpcDataSourceEntity> opcDataSourceEntities)
           : base(deviceEntity, workshopCommunicationService)
        {
            _opcDataSourceEntities = opcDataSourceEntities;
            CheckOutDataType();
        }

        private void CheckOutDataType()
        {
            //对所有OPC 数据类型进行校验，如果不对记入LOG

        }


        public override void InitalDevice()
        {
            //创建opc 订阅  就分成一个通道，数据收集由LineManager完成


            //状态通道  程序号；状态  模式
            var subscriptionStatus = _opcDataSourceEntities.Where(i => i.DataAction == 4);
            //找出订阅数据的服务器列表
            var serverIds = subscriptionStatus.Select(i => i.ServerId).Distinct();


            if (serverIds.Count() == 1)
            {
                opcServiceId = serverIds.First();
                _workshopCommunicationService.CreateOpcSubscription(subscriptionStatus, DataHandler);
            }

            //创建tcp 监听
            //tcpListener = new TcpListening("192.168.1.235:11255");
            //tcpListener.TcpDataRecivedHandler += TcpListener_TcpDataRecivedHandler;
            //tcpListener.DoConnect();
        }

        

        private void DataHandler(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e)
        {
            try
            {
                MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification;
                //Console.WriteLine(notification.Value.StatusCode.ToString());

                if (notification != null)
                {
                    Guid dataId = new Guid();
                    bool isId = Guid.TryParse(monitoredItem.DisplayName, out dataId);
                    if (isId && (!dataId.IsGuidNullOrEmpty()))
                    {
                        var dataSource = _opcDataSourceEntities.Where(i => i.Id == dataId).First();
                        switch (dataSource.DataName)
                        {
                            case "BypassStatus":
                                {
                                    BypassStatus = (bool)notification.Value.Value;
                                    break;
                                }
                            case "Ready":
                                {
                                    Ready = (bool)notification.Value.Value;
                                    break;
                                }
                            case "End":
                                {
                                    End = (bool)notification.Value.Value;
                                    break;
                                }
                            case "HasWorkpiece":
                                {
                                    HasWorkpiece = (bool)notification.Value.Value;
                                    break;
                                }
                            case "WorkpieceSource":
                                {
                                    WorkpieceSource = (short)notification.Value.Value;
                                    break;
                                }
                            case "GetResult":
                                {
                                    GetResult = ((bool)notification.Value.Value).ToString()+"|"+notification.Value.SourceTimestamp;
                                    break;
                                }
                            default:
                                {
                                    break;
                                }
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #region 获取三坐标测量结果
        public List<string> GetThreeCoordinatesResult()
        {
            List<string> result = new List<string>();

            List<string> tags = new List<string>()
            {
                "ns=2;s=Xibei01.MainPlcControl.ThreeCoordinatesMeasure.ProductionData.Result1_1",
                "ns=2;s=Xibei01.MainPlcControl.ThreeCoordinatesMeasure.ProductionData.Result2_1",
                "ns=2;s=Xibei01.MainPlcControl.ThreeCoordinatesMeasure.ProductionData.Result3_1",
                "ns=2;s=Xibei01.MainPlcControl.ThreeCoordinatesMeasure.ProductionData.Result4_1",
                "ns=2;s=Xibei01.MainPlcControl.ThreeCoordinatesMeasure.ProductionData.Result5_1",
                "ns=2;s=Xibei01.MainPlcControl.ThreeCoordinatesMeasure.ProductionData.Result6_1",
                "ns=2;s=Xibei01.MainPlcControl.ThreeCoordinatesMeasure.ProductionData.Result7_1",
                "ns=2;s=Xibei01.MainPlcControl.ThreeCoordinatesMeasure.ProductionData.Result8_1",
                "ns=2;s=Xibei01.MainPlcControl.ThreeCoordinatesMeasure.ProductionData.Result9_1",
                "ns=2;s=Xibei01.MainPlcControl.ThreeCoordinatesMeasure.ProductionData.Result10_1",
                "ns=2;s=Xibei01.MainPlcControl.ThreeCoordinatesMeasure.ProductionData.Result11_1",
                "ns=2;s=Xibei01.MainPlcControl.ThreeCoordinatesMeasure.ProductionData.Result12_1",
                "ns=2;s=Xibei01.MainPlcControl.ThreeCoordinatesMeasure.ProductionData.Result13_1",
                "ns=2;s=Xibei01.MainPlcControl.ThreeCoordinatesMeasure.ProductionData.Result14_1",
                "ns=2;s=Xibei01.MainPlcControl.ThreeCoordinatesMeasure.ProductionData.Result15_1",
                "ns=2;s=Xibei01.MainPlcControl.ThreeCoordinatesMeasure.ProductionData.Result16_1",
                "ns=2;s=Xibei01.MainPlcControl.ThreeCoordinatesMeasure.ProductionData.Result17_1",
                "ns=2;s=Xibei01.MainPlcControl.ThreeCoordinatesMeasure.ProductionData.Result18_1",
                "ns=2;s=Xibei01.MainPlcControl.ThreeCoordinatesMeasure.ProductionData.Result19_1",
                "ns=2;s=Xibei01.MainPlcControl.ThreeCoordinatesMeasure.ProductionData.Result20_1",
                "ns=2;s=Xibei01.MainPlcControl.ThreeCoordinatesMeasure.ProductionData.Result21_1"
            };

            try
            {
                List<DataValue> dataValues = _workshopCommunicationService.ReadValues(opcServiceId, tags);
                if (dataValues != null)
                {
                    for(int i = 0; i < dataValues.Count; i++)
                    {
                        if (dataValues[i] != null)
                        {
                            result[i] = dataValues[i].Value.ToString();
                        }
                    }
                }
            }
            catch(Exception ex)
            {

            }                       
            return result;
        }

        #endregion

        #region 设备参数
        private bool bypassStatus;
        public bool BypassStatus
        {
            get
            {
                return bypassStatus;
            }
            set
            {
                bool previewVlaue = bypassStatus;
                bypassStatus = value;
                OnPropertyChanged("BypassStatus", previewVlaue, bypassStatus);
            }
        }

        private bool ready;
        public bool Ready
        {
            get
            {
                return ready;
            }
            set
            {
                bool previewVlaue = ready;
                ready = value;
                OnPropertyChanged("Ready", previewVlaue, ready);
            }
        }

        private bool end;
        public bool End
        {
            get
            {
                return end;
            }
            set
            {
                bool previewVlaue = end;
                end = value;
                OnPropertyChanged("End", previewVlaue, end);
            }
        }

        private bool hasWorkpiece;
        public bool HasWorkpiece
        {
            get
            {
                return hasWorkpiece;
            }
            set
            {
                bool previewVlaue = hasWorkpiece;
                hasWorkpiece = value;
                OnPropertyChanged("HasWorkpiece", previewVlaue, hasWorkpiece);
            }
        }

        private short workpieceSource;
        public short WorkpieceSource
        {
            get
            {
                return workpieceSource;
            }
            set
            {
                short previewVlaue = workpieceSource;
                workpieceSource = value;
                OnPropertyChanged("WorkpieceSource", previewVlaue, workpieceSource);
            }
        }

        private string getResult;
        /// <summary>
        /// 获取三坐标的值提示
        /// 由于将这个提示发给LinePlantService后，记录到数据库需要用到时间，所以，该类型用string替代
        /// 格式：boolean|Datetime
        /// </summary>
        public string GetResult
        {
            get
            {
                return getResult;
            }
            set
            {
                string previewValue = getResult;
                getResult = value;
                OnPropertyChanged("GetResult", previewValue, getResult);
            }
        }
        #endregion

        #region 三坐标TCP方法    暂时不用
        private void TcpListener_TcpDataRecivedHandler(object sender, TcpDataRecivedEventArgs e)
        {
            DecodeTcpResponse(e);
        }


        private void DecodeTcpResponse(TcpDataRecivedEventArgs e)
        {
            if(e.IpPort==tcpListener.ClientsIpPort)
            {

            }

            string[] ip = e.IpPort.Split(':');
            string data = e.ToString();
            string[] splitData = data.Split(':');
        }


        private string ParaseCommand(string command)
        {

            //102:e\chanpin\\aaa.ksln    打开检测文件
            //202： 设备是否空闲 1：空闲 0：不空闲
            //108:115:1047:-222
            //103:1


            string[] commands = command.Split(':');
            if (commands.Length == 2)
            {

                return "102:e" + "\\" + "chanpin" + "\\" + "\\" + "aaa.ksln";
            }
            else
                return command;
        }


        bool isSending = false;
        string currentCommand = "0";

        public async Task<string> SendCommand(string command, string data)
        {
            if(!isSending)
            {
                isSending = true;
                currentCommand = command;
                string message = currentCommand + ":" + data;
                tcpListener.SendData(message);
                await Task.Delay(1000);

                if(messageResponseContent.Command==currentCommand)
                {

                }

                currentCommand = "0";
                isSending = false;
                
            }
            return null;
        }

    }


    public class MessageResponseContent
    {

        /// <summary>
        /// command
        /// </summary>
        public string Command { get; set; } = "0";

        /// <summary>
        /// 答复内容
        /// </summary>
        public string ResponseData { get; set; }

        /// <summary>
        /// 答复时间
        /// </summary>
        public DateTime ResponseTime { get; set; }

    }
    #endregion

}
